<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12" :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <el-card style="margin-bottom: 20px">
          <template #header>
            <div class="card-header">
              <span>提问列表</span>
            </div>
          </template>

          <VTable
            :tableData="quesData"
            :options="quesOptions"
            @getSelection="handleSelection"
            @clickRow="handleClickRow"
          >
            <template #menubtn>
              <el-button type="primary" @click="quesHandleAdd">新增</el-button>
              <el-button type="warning" @click="handleBatchDelete"
                >批量删除</el-button
              >
            </template>

            <template #operate="scope">
              <el-button
                size="small"
                link
                type="primary"
                :icon="View"
                @click="handleDetail(scope.row)"
                >查看</el-button
              >
              <el-button
                size="small"
                link
                type="primary"
                :icon="Edit"
                @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                link
                type="danger"
                :icon="Delete"
                @click="handleDelete(scope.row.id)"
                >删除</el-button
              >
            </template>
          </VTable>
        </el-card>
      </el-col>

      <el-col :span="12" :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>回复列表</span>
            </div>
          </template>

          <VTable :options="ansOptions" :tableData="ansData">
            <template #menubtn>
              <el-button type="primary" @click="ansHandleAdd">新增</el-button>
            </template>
            <template #operate="scope">
              <!-- <el-button
                size="small"
                link
                type="primary"
                :icon="Edit"
                @click="ansHandleEdit(scope.row)"
                >编辑</el-button
              > -->
              <el-button
                size="small"
                link
                type="danger"
                :icon="Delete"
                @click="ansHandleDelete(scope.row.id)"
                >删除</el-button
              >
            </template>
          </VTable>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      style="width: 600px"
    >
      <el-form
        v-if="actionType === '新增' || actionType === '编辑'"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item
          v-for="item in filterOptions"
          :key="item"
          :label="item.label"
          :prop="item.prop"
        >
          <el-autocomplete
            :clearable="true"
            v-if="item.prop === 'title'"
            v-model="ruleForm[item.prop]"
            :fetch-suggestions="querySearchHomestay"
            class="inline-input w-50"
            @select="handleSelectHomestay"
          />
          <el-autocomplete
            :clearable="true"
            v-else-if="item.prop === 'username'"
            v-model="ruleForm[item.prop]"
            :fetch-suggestions="querySearchUsername"
            class="inline-input w-50"
            @select="handleSelectUsername"
          />
          <el-input
            v-else
            v-model="ruleForm[item.prop]"
            :rows="3"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- 详情 -->
      <Description
        v-if="actionType === '查看'"
        :options="quesOptions"
        :dataItem="dataItem"
      ></Description>

      <template #footer>
        <el-button
          v-if="actionType === '新增' || actionType === '编辑'"
          @click="resetForm(ruleFormRef)"
          >关闭</el-button
        >
        <el-button v-if="actionType === '查看'" @click="dialogVisible = false"
          >关闭</el-button
        >
        <el-button
          v-if="actionType === '新增' || actionType === '编辑'"
          type="primary"
          @click="submitForm(ruleFormRef)"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 回复的弹窗 -->
    <el-dialog
      v-model="ansDialogVisible"
      :title="ansDialogTitle"
      style="width: 600px"
    >
      <!--新增/编辑  -->
      <el-form
        v-if="ansActionType === '新增' || ansActionType === '编辑'"
        ref="ruleFormRef"
        :model="ansRuleForm"
        :rules="ansRules"
        label-width="auto"
      >
        <el-form-item
          v-for="item in ansFilterOptions"
          :key="item"
          :label="item.label"
          :prop="item.prop"
        >
          <el-autocomplete
            v-if="item.prop === 'username'"
            v-model="ansRuleForm[item.prop]"
            :fetch-suggestions="querySearchAnsUser"
            clearable
            class="inline-input w-50"
            @select="handleSelectAnsUser"
          />
          <el-input
            v-else-if="item.prop === 'content'"
            v-model="ansRuleForm[item.prop]"
            :rows="3"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="resetForm(ruleFormRef)">关闭</el-button>

        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import {
  getAllQues,
  addQues,
  deleteQues,
  batchDeleteQues,
  updateQues,
  getAnswer,
  addAns,
  deleteAns,
} from "../../api/QandAManage/index";
import VTable from "../../components/VTable/index.vue";
import Description from "../../components/Description/index.vue";
import { Delete, Edit, View, Plus, List } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import {
  getAllHomestay,
  searchHomestayByTitle,
  searchOnlineHomeByTitle,
  getAllOnlineHomeList,
} from "../../api/homestayManage/index";
import {
  getGuest,
  searchGuest,
  getUserByOrder,
  searchOrderGuestByname,
} from "../../api/userManage/index";
import { ElMessage, ElMessageBox } from "element-plus";

const quesData = ref<any>([]);
const quesOptions = [
  {
    prop: "username",
    label: "提问者",
    isTable: true,
    isForm: true,
  },
  {
    prop: "title",
    label: "房源",
    width: 180,
    isTable: true,
    isForm: true,
  },
  {
    prop: "content",
    label: "内容",
    isTable: true,
    width: 180,
    isForm: true,
  },
  {
    prop: "createTime",
    label: "创建时间",
    isTable: true,
    width: 180,
    type: "time",
  },
];
const ansData = ref<any>([]);
const ansOptions = [
  {
    prop: "username",
    label: "回复者",
    isTable: true,
    isForm: true,
  },
  {
    prop: "content",
    label: "内容",
    isTable: true,
    isForm: true,
    width: 200,
  },
  {
    prop: "createTime",
    label: "回复时间",
    isTable: true,
    width: 200,
    type: "time",
  },
];

const filterOptions = quesOptions.filter((item) => item.isForm == true);
const ansFilterOptions = ansOptions.filter((item) => item.isForm == true);

const ruleFormRef = ref<FormInstance>();
let ruleForm = reactive({
  userId: "",
  homeId: "",
  content: "",
});
const rules = reactive<FormRules>({
  username: [
    { required: true, message: "请选择评论人", trigger: ["blur", "change"] },
  ],
  title: [
    { required: true, message: "请选择房源", trigger: ["blur", "change"] },
  ],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
});
const dialogTitle = ref("查看"); // 弹出层标题
const dialogVisible = ref<boolean>(false);
const actionType = ref(""); // 操作按钮的类型
const setDialogTile = (type: string) => {
  dialogTitle.value = type;
  actionType.value = type;
  dialogVisible.value = true;
};
//新增
const quesHandleAdd = () => {
  ruleForm = reactive({
    userId: "",
    homeId: "",
    content: "",
  });
  setDialogTile("新增");
};
//详情
const dataItem = ref<object>({});
const handleDetail = (scope: any) => {
  dataItem.value = scope;
  setDialogTile("查看");
};
//编辑
const handleEdit = async (scope: any) => {
  ruleForm = scope;
  console.log(ruleForm);
  setDialogTile("编辑");
};
//删除
const handleDelete = (id: number) => {
  ElMessageBox.confirm("确认删除此项数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteQues(id);
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      await onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
//子组件传值--多选
const ids = ref<any>([]);
const handleSelection = (val: any) => {
  console.log("子组件传值：", val);
  const selecction: any = [];
  val.forEach((item: any) => {
    selecction.push(item.id);
  });
  ids.value = selecction;
};
// 批量删除
const handleBatchDelete = async () => {
  if (ids.value.length == 0) {
    ElMessage({
      type: "info",
      message: "请选择数据",
    });
    return;
  }
  ElMessageBox.confirm("确认删除这些数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await batchDeleteQues({ ids: ids.value });
      if (res.data.success) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      await onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//自动补全
const querySearchHomestay = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchOnlineHomeByTitle({ title: name });
    res.data.data.forEach((item) => {
      list.push({ value: item.title, id: item.id });
    });
  } else {
    const res = await getAllOnlineHomeList();
    res.data.data.forEach((item) => {
      list.push({ value: item.title, id: item.id });
    });
  }
  callback(list);
};
const querySearchUsername = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchGuest({ username: name });
    res.data.data.forEach((item) => {
      list.push({ value: item.username, id: item.id });
    });
  } else {
    const res = await getGuest();
    res.data.data.forEach((item) => {
      list.push({ value: item.username, id: item.id });
    });
  }
  callback(list);
};
//选中
const handleSelectHomestay = (item, $event) => {
  ruleForm.homeId = item.id;
};
const handleSelectUsername = (item, $event) => {
  ruleForm.userId = item.id;
};

// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  console.log(ruleForm);
  if (actionType.value === "新增") {
    const res = await addQues(ruleForm);
    if (res.data.success == true) {
      ElMessage({
        message: res.data.msg,
        type: "success",
      });
      onLoad();
    } else {
      ElMessage.error(res.data.msg);
    }
  } else if (actionType.value === "编辑") {
    const res = await updateQues(ruleForm);
    if (res.data.success) {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
        onLoad();
      } else {
        ElMessage.error(res.data.msg);
      }
    }
  } else if (ansActionType.value == "编辑") {
    const res = await updateReply(ansRuleForm);
    if (res.data.success) {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
        await getNewReply(clickId.value);
      } else {
        ElMessage.error(res.data.msg);
      }
    }
  } else if (ansActionType.value == "新增") {
    console.log("111", ansRuleForm);
    const res = await addAns(ansRuleForm);
    if (res.data.success) {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
        await getNewAnswer();
      } else {
        ElMessage.error(res.data.msg);
      }
    }
  }
  dialogVisible.value = false;
  ansDialogVisible.value = false;
};
//关闭
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  if (actionType.value === "新增") {
    formEl.resetFields();
  }
  dialogVisible.value = false;
  ansDialogVisible.value = false;
};

//房源id
const homeId = ref<number>();
const clickId = ref<number>();
//子组件传值--点击行
const handleClickRow = async (val: any) => {
  homeId.value = val.homeId; //根据房源id查订单的用户
  clickId.value = val.id;
  const res = await getAnswer(val.id);
  ansData.value = res.data.data;
};
const getNewAnswer = async () => {
  const res = await getAnswer(clickId.value);
  console.log(res);
  ansData.value = res.data.data;
};

let ansRuleForm = reactive({
  userId: Number,
  quesId: Number,
  content: "",
});
const ansRules = reactive<FormRules>({
  username: [
    { required: true, message: "请选择回复者", trigger: ["blur", "change"] },
  ],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
});
//子组件新增编辑
const ansDialogTitle = ref("查看"); // 弹出层标题
const ansDialogVisible = ref<boolean>(false);
const ansActionType = ref(""); // 操作按钮的类型
const setAnsDialogTile = (type: string) => {
  ansDialogTitle.value = type;
  ansActionType.value = type;
  ansDialogVisible.value = true;
};
//新增
const ansHandleAdd = () => {
  ansRuleForm = reactive({
    userId: "",
    quesId: clickId.value,
    content: "",
  });
  setAnsDialogTile("新增");
};
//自动补全
const querySearchAnsUser = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchOrderGuestByname({
      username: name,
      homeId: homeId.value,
    });
    res.data.data.forEach((item) => {
      list.push({ value: item.username, id: item.id });
    });
  } else {
    const res = await getUserByOrder(homeId.value);
    res.data.data.forEach((item) => {
      list.push({ value: item.username, id: item.id });
    });
  }
  callback(list);
};
//选中
const handleSelectAnsUser = (item, $event) => {
  ansRuleForm.userId = item.id;
};

//删除
const ansHandleDelete = (id: number) => {
  ElMessageBox.confirm("确认删除此项数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteAns(id);
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      await getNewAnswer();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const onLoad = async () => {
  const res = await getAllQues();
  quesData.value = res.data.data;
};
onMounted(async () => {
  await onLoad();
});
</script>

<style lang="scss" scoped></style>
